<template>
    <div class="user-info-container">
        <h3 class="title">我的信息</h3>

        <!-- 显示用户信息 -->
        <el-form :model="userInfo" label-width="120px" class="user-info-form">
            <el-form-item label="用户ID">
                <el-input v-model="userInfo.user_id" disabled />
            </el-form-item>

            <el-form-item label="用户名">
                <el-input v-model="userInfo.name" />
            </el-form-item>

            <el-form-item label="密码">
                <el-input type="password" v-model="userInfo.password" />
            </el-form-item>

            <el-form-item label="电话">
                <el-input v-model="userInfo.phone" />
            </el-form-item>

            <el-form-item label="邮箱">
                <el-input v-model="userInfo.email" />
            </el-form-item>

            <el-form-item label="性别">
                <el-select v-model="userInfo.sex" placeholder="请选择性别">
                    <el-option label="男" value="male" />
                    <el-option label="女" value="female" />
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="updateUserInfo" class="update-button">更新信息</el-button>
            </el-form-item>
        </el-form>
    </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { userApi } from '@/request/apiService';

// 存储用户信息
const userInfo = ref({});

// 获取用户信息
const fetchUserInfo = async () => {
    const { data } = await userApi.getUserList();
    userInfo.value = data;
};

// 更新用户信息
const updateUserInfo = async () => {
    const updatedInfo = { ...userInfo.value };

    // 删除没有修改的字段
    Object.keys(updatedInfo).forEach(key => {
        if (!updatedInfo[key]) {
            delete updatedInfo[key];
        }
    });

    await userApi.updateUser(updatedInfo);
    fetchUserInfo(); // 重新加载用户信息
};

// 初始化加载用户信息
onMounted(fetchUserInfo);
</script>

<style scoped>
.user-info-container {
    max-width: 700px;
    margin: 30px auto;
    padding: 20px;
    background-color: #f0f9ff;
    border-radius: 8px;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.title {
    font-size: 24px;
    font-weight: bold;
    margin-bottom: 20px;
    text-align: center;
    color: #409eff;
}

.user-info-form .el-form-item {
    margin-bottom: 15px;
}

.el-input,
.el-select {
    width: 100%;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    background-color: #ffffff;
}

.update-button {
    width: 100%;
    margin-top: 20px;
    padding: 10px;
    background-color: #409eff;
    color: white;
    border: none;
    border-radius: 4px;
    font-weight: bold;
}

.update-button:hover {
    background-color: #66b1ff;
}
</style>
